<template>
  <div v-if="mixinState.mSelectMode === 'one' && type === 'image'" class="box attr-item">
    <Button @click="repleace" type="text" long>本地图片</Button>
    <Button @click="state.showModal = true" type="text" long>url图片</Button>
  </div>
  <div>
    <!-- 插入字符串svg元素 -->
    <Modal
      v-model="state.showModal"
      title="替换图片"
      @on-ok="urlRepleace()"
      @on-cancel="
        () => {
          state.showModal = false;
          state.imgUrl = '';
        }
      "
    >
      <Input
        v-model="state.imgUrl"
        show-word-limit
        type="textarea"
        :placeholder="state.placeholder"
      />
    </Modal>
  </div>
</template>

<script setup name="ReplaceImg">
import useSelect from '@/hooks/select';

import { getImgStr, selectFiles, insertImgFile } from '@/utils/utils';

const state = reactive({
  showModal: false,
  imgUrl: '',
  placeholder: '请输入图片url地址',
});

const update = getCurrentInstance();
const event = inject('event');
const { mixinState, canvasEditor } = useSelect();
const type = ref('');

// 替换图片
const repleace = async () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  if (activeObject && activeObject.type === 'image') {
    const [file] = await selectFiles({ accept: 'image/*', multiple: false }); // 图片
    const fileStr = await getImgStr(file); // 转字符串
    const imgEl = await insertImgFile(fileStr); // 字符串转El
    const width = imgEl.width;
    const height = imgEl.height;
    const scaleX = activeObject.get('scaleX');
    const scaleY = activeObject.get('scaleY');
    activeObject.setSrc(imgEl.src, () => {
      activeObject.set('scaleX', (width * scaleX) / imgEl.width);
      activeObject.set('scaleY', (height * scaleY) / imgEl.height);
      canvasEditor.canvas.renderAll();
    });
    imgEl.remove();
  }
};

const urlRepleace = () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  if (activeObject && activeObject.type === 'image') {
    let imgUrl = state.imgUrl;
    state.imgUrl = '';
    let image = new Image();
    image.src = imgUrl + '?v=' + Math.random(); // 处理缓存
    image.crossOrigin = '*'; // 支持跨域图片
    image.onload = async () => {
      let canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      let ctx = canvas.getContext('2d');
      ctx.drawImage(image, 0, 0, image.width, image.height);
      let fileStr = canvas.toDataURL('image/png');
      const imgEl = await insertImgFile(fileStr); // 字符串转El
      const width = image.width;
      const height = image.height;
      const scaleX = activeObject.get('scaleX');
      const scaleY = activeObject.get('scaleY');
      activeObject.setSrc(imgEl.src, () => {
        activeObject.set('scaleX', (width * scaleX) / imgEl.width);
        activeObject.set('scaleY', (height * scaleY) / imgEl.height);
        canvasEditor.canvas.renderAll();
      });
      imgEl.remove();
      state.showModal = false;
      state.placeholder = imgUrl;
    };
  }
};

const init = () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  if (activeObject) {
    type.value = activeObject.type;
    update?.proxy?.$forceUpdate();
  }
};

onMounted(() => {
  event.on('selectOne', init);
});

onBeforeUnmount(() => {
  event.off('selectOne', init);
});
</script>
